package com.nbjtjc.safe.service.emg;

import cn.hutool.core.collection.CollectionUtil;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.emg.EmgPlanGoodsMapper;
import com.nbjtjc.safe.mapper.emg.EmgPlanMapper;
import com.nbjtjc.safe.model.emg.EmgPlan;
import com.nbjtjc.safe.model.sys.SysUser;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class EmgPlanService {

    @Autowired
    private EmgPlanMapper emgPlanMapper;

    @Autowired
    private EmgPlanGoodsMapper emgPlanGoodsMapper;


    @Transactional(rollbackFor = {Throwable.class})
    public Result add(EmgPlan emgPlan) {
        Result result = new Result();
        if (emgPlan.getTypeId() == null || emgPlan.getTypeId() == 0) {
            return result;
        }
        SysUser sysUser= (SysUser) SecurityUtils.getSubject().getSession().getAttribute("user");
        emgPlan.setCreateUserId(sysUser.getUserId());
        emgPlan.setCreateDate(new Date());
        emgPlan.setCompanyId(MyShiroUtils.getCompanyId());
        emgPlan.setDeptId(MyShiroUtils.getDeptId());
        int ans = emgPlanMapper.insertSelective(emgPlan);
        if (ans != 1) {
            result.setFalse("插入失败");
            return result;
        }
        if (CollectionUtil.isNotEmpty(emgPlan.getEmgPlanGoods())) {
            emgPlan.getEmgPlanGoods().forEach(emgPlanGoods -> {
                emgPlanGoods.setPlanId(emgPlan.getId());
            });
            emgPlanGoodsMapper.insertList(emgPlan.getEmgPlanGoods());
        }
        result.setData(emgPlan);
        return result;
    }

    @Transactional(rollbackFor = {Throwable.class})
    public Result update(EmgPlan emgPlan) {
        Result result = new Result();
        if (emgPlan.getTypeId() == null || emgPlan.getTypeId() == 0) {
            return result;
        }
        int ans = emgPlanMapper.updateByPrimaryKeySelective(emgPlan);
        if (ans != 1) {
            result.setFalse("更新失败");
            return result;
        }
        emgPlanGoodsMapper.deleteByPlanId(emgPlan.getId());
        if(CollectionUtil.isNotEmpty(emgPlan.getEmgPlanGoods())){
            emgPlan.getEmgPlanGoods().forEach(emgPlanGoods -> {
                emgPlanGoods.setPlanId(emgPlan.getId());
            });
            emgPlanGoodsMapper.insertList(emgPlan.getEmgPlanGoods());
        }
        return result;
    }


}
